#ifndef BLUETOOTH_MANAGER_H
#define BLUETOOTH_MANAGER_H

#include <Arduino.h>
#include <BluetoothSerial.h>
#include <ArduinoJson.h>
#include <functional>

// 蓝牙状态枚举
enum BluetoothState {
    BT_DISABLED,
    BT_INITIALIZING,
    BT_READY,
    BT_CONNECTED,
    BT_ERROR
};

class BluetoothManager {
private:
    BluetoothSerial* btSerial;
    BluetoothState currentState;
    String deviceName;
    bool isEnabled;
    bool autoDisableAfterWiFi;
    unsigned long lastHeartbeat;
    String connectedDeviceName;
    
    // 命令处理回调函数
    std::function<String(const String&)> commandHandler;
    std::function<void(const String&, const String&)> wifiConfigHandler;
    
    // 内部方法
    void processIncomingData();
    void handleBluetoothCommand(const String& command);
    void handleWiFiConfig(const String& ssid, const String& password);
    void sendResponse(const String& response);
    void sendJSON(const String& command, bool success, const String& message = "", const String& data = "");
    String parseCommand(const String& input);
    bool parseWiFiConfig(const String& input, String& ssid, String& password);
    
    // 蓝牙事件回调
    static void onBluetoothCallback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param);

public:
    BluetoothManager();
    ~BluetoothManager();
    
    // 初始化和控制
    bool initialize(const String& name = "sandart");
    void enable();
    void disable();
    bool isBluetoothEnabled() const;
    BluetoothState getState() const;
    
    // 连接管理
    bool isConnected() const;
    String getConnectedDevice() const;
    void disconnect();
    
    // 配置
    void setDeviceName(const String& name);
    void setAutoDisableAfterWiFi(bool enable);
    void setCommandHandler(std::function<String(const String&)> handler);
    void setWiFiConfigHandler(std::function<void(const String&, const String&)> handler);
    
    // 运行时更新
    void update();
    
    // 数据发送
    void sendMessage(const String& message);
    void sendStatus(const String& status);
    void sendHeartbeat();
    
    // 状态查询
    void printStatus();
    String getStatusJSON();
    
    // 静态回调处理
    static BluetoothManager* instance;
    void handleCallback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param);
};

#endif // BLUETOOTH_MANAGER_H
